<template>
  <div style="--wails-draggable:drag;position: relative;">
    <img ref="ocrImg" :src="imgageBase64" />
    <div style="position: absolute;width: 100vw;height: 100vh;z-index: 999;top: 0;" @dblclick="close">
      <div v-for="(item, index) in boxList"
        style="position: absolute;border: 1px solid green; color: greenyellow ;--wails-draggable:no-drag;display: flex;align-items: center;background-color: rgba(0, 0, 0, .5);"
        :style="{ width: item.width, height: item.height, top: item.position.top, left: item.position.left, fontSize: item.fontSize }">
        {{ textList[index] }}
      </div>
    </div>
  </div>
</template>
<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { Events, Window } from "@wailsio/runtime";
import { useRoute } from "vue-router"
import * as ocr from '@paddle-js-models/ocr';

const urlTime = useRoute().query?.time
const imgageBase64 = ref('')
const ocrImg = ref()
const boxList = ref([])
const textList = ref([])
Events.On('showCutImage', (event) => {
  const time = event.data[1]
  if (time == urlTime) {
    imgageBase64.value = event.data[0]
    nextTick(() => {
      // "/ocr/det/model.json", "/ocr/rec/model.json"
      ocr.init("/ocr/det/model.json", "/ocr/rec/model.json").then(() => {
        console.log('ocr初始化完成！');
        ocr.recognize(ocrImg.value).then(res => {
          // 打印OCR模型得到的文本坐标以及文本内容
          console.log(res);
          computeBox(res.points)
          textList.value = res.text.map(item => item.replaceAll('\r', ''))
        })
      })
    })
  }
});

window.addEventListener(
  "keydown",
  (event) => {
    const keyName = event.key;
    console.log('keydown--->', keyName)
    if (keyName === "Escape") {
      close()
    }
  },
  false,
);

function close() {
  console.log('keydown')
  Window.Close()
}

function boxSizeWidth(pointList) {
  console.log(pointList)
  const width = pointList[2][0] - pointList[0][0]
  console.log(width)
  return width
}

function boxSizeHeight(pointList) {
  return pointList[2][1] - pointList[0][1]
}

function computeBox(boxPointList) {
  boxList.value = boxPointList.map(pointList => {
    const width = pointList[2][0] - pointList[0][0]
    const height = pointList[2][1] - pointList[0][1]
    const position = {
      left: pointList[0][0] + 'px',
      top: pointList[0][1] + 'px'
    }
    let fontSize = 14
    // if (height > width) {
    //   fontSize = width - 8
    // } else {
    //   fontSize = height - 8
    // }
    // if (fontSize < 12) {
    //   fontSize = 12
    // }
    return {
      width: width + 'px',
      height: height + 'px',
      fontSize: fontSize + 'px',
      position
    }
  })
}
</script>
<style scoped></style>